<?php
/**
 * Created by PhpStorm.
 * User: 张福来
 * Date: 2018/10/27
 * Time: 11:38
 */
namespace app\api\controller;
use app\api\model\User;
use think\Config;
use think\Request;

/*
* Notes: 登录模块
* Create Date: 2018/10/27
* Create Time: 11:39
* Create by :张福来
* Param :
*/
class Login extends Base{
    /*
    * Notes: 商户登录
    * Create Date: 2018/10/27
    * Create Time: 11:43
    * Create by :张福来
    * Param :
    */
    public function cashlogin(){
        
    }
    /*
    * Notes: 获取用户 openid
    * Create Date: 2018/10/29
    * Create Time: 16:33
    * Create by :张福来
    * Param :
    */
    public function getOpenid(){
        $user = new User;
        $js_code = input('post.js_code');
//        $appId = "wxf8d86d8a5d32393c";
        $appId = config("wxConfig.appId");
//        $appKey = "89d26e80f1b717e6d152aa8d5c182c81";
        $appKey = config("wxConfig.appKey");
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appKey&js_code=$js_code&grant_type=authorization_code";
        $returndate = json_decode($this -> curl("",$url) ,true);
        file_put_contents('1.txt', json_encode($returndate));
        if (empty($returndate['errcode'])) {
            $w['openid'] = $returndate["openid"];
            // cache($w['openid'],$returndate["session_key"]);
            $userin = $user->checkUserLogin($w);
            echo json_encode($returndate);
            exit();
        }
        echo "";
        exit();
    }

    public function curl($data,$url){

        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $headers = array(
            'content-type:'.'application/json'
        );
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        return $file_contents;
    }
    /*
    * Notes: 用户登录
    * Create Date: 2018/10/29
    * Create Time: 16:33
    * Create by :张福来
    * Param :
    */
    public function userlogin(Request $request){
        $user = new User;
        $userinfo = $request->post();
        $requestip = Request::instance();

        // if(!empty($userinfo["phone"])){
        //     $data['phone'] =  $userinfo["phone"];//同步数据的唯一标识 -- 手机号
        // }
        if (!$userinfo) {
            return apiResponse("201","授权失败","");
        }
        if(empty($userinfo['openid'])){
            return apiResponse("201","openid不能为空","");
        }
        // if(empty($userphone)){
        //        $w['openid']=trim(userinfo["openid"]);
            $w['openid'] = $userinfo["openid"];
            $w['status'] = array('neq',9);
            $userin = $user->checkUserLogin($w);
            $uid = $userin['u_id'];
            if ($uid) {//有用户更新数据
                $save['num'] = $userin['num'] +1;
                $save['last_login_time'] = time();
                $save['last_login_ip'] =$requestip->ip();
                $con = array("u_id"=>intval($uid));
                $changenum =$user->updateUser($save,$con);
                if($changenum){
                    $userin['u_id'] = intval($uid);
                    $userin['last_login_ip'] = $requestip->ip();
                    return apiResponse("200","授权成功",$userin);
                }
            }else{//无用户
                $data['nickName'] = $userinfo['nickName'];
                $data['name'] = $userinfo['nickName'];
                $data['head_pic'] = $userinfo['avatarUrl'];
                $data['sex'] = $userinfo['gender'];
                $data['password'] = md5("123456");
                $data['openid'] = $userinfo["openid"];
                if(!empty($userinfo['unionid'])){
                    $data['unionid'] = $userinfo['unionid'];
                }else{
                    $data['unionid'] = "";
                }
                if(!empty($userinfo['p_id'])){
                    $haspuser = $user->checkUserLogin( array('u_id' => $userinfo['p_id'],'status'=>array('neq',9)));
                    if (!empty($haspuser)) {
                        $data['p_id'] = $userinfo['p_id'];
                    }
                    
                }
                $data['ctime'] = time();
                $data['utime'] = time();
                $data['last_login_time'] = time();
                $data['last_login_ip'] =$requestip->ip();
                if (!$data['openid']) {
                    return apiResponse("201","授权失败","");
                }
                $data['joinpic'] = "joinpic/".time().".jpg";
                $res = $user->addUser($data);
                if ($res) {
                    //           $err = array();
                    $data['u_id'] = intval($res);
                    $this->getJoinPic($data['u_id'],$data['joinpic']);
                    return apiResponse("200","授权成功",$data);
                }else{
                    return apiResponse("201","授权失败","");
                }
            }
        // }else{
        //     $checkphone = $user->checkphone($userphone);//查询用户是否已经有账号
        //     if($checkphone['u_id']){ //如果有 更新数据
        //         $data['nickName'] = $userinfo['nickName'];
        //         $data['head_pic'] = $userinfo['avatarUrl'];
        //         $data['sex'] = $userinfo['gender'];
        //         $data['password'] = md5("123456");
        //         $data['openid'] = $userinfo["openid"];
        //         $con = array("u_id"=>intval($checkphone['u_id']));

        //         $changenum =$user->updateUser($data,$con);
        //         if($changenum){
        //             $returndata = $user->selecUser(1,1,['u_id'=>$checkphone['u_id']]);
        //             return apiResponse("200","授权成功",$returndata);
        //         }
        //     }else{//没有账号 添加用户
        //         $data = array();
        //         $data['nickName'] = $userinfo['nickName'];
        //         $data['head_pic'] = $userinfo['avatarUrl'];
        //         $data['sex'] = $userinfo['gender'];
        //         $data['password'] = md5("123456");
        //         $data['openid'] = $userinfo["openid"];
        //         $data['phone'] = $userphone;
        //         $data['last_login_time'] = time();
        //         $data['last_login_ip'] = $requestip->ip();
        //         if(!empty($userinfo['unionid'])){
        //             $data['unionid'] = $userinfo['unionid'];
        //         }else{
        //             $data['unionid'] = "";
        //         }
        //         if(!empty($userinfo['p_id'])){
        //             $data['p_id'] = $userinfo['p_id'];
        //         }
        //         $data['ctime'] = time();
        //         $data['utime'] = time();
        //         $data['last_login_time'] = time();
        //         if (!$data['openid']) {
        //             return apiResponse("201","授权失败","");
        //         }
        //         $data['joinpic'] = "joinpic/".time().".jpg";
        //         $res = $user->addUser($data);
        //         if ($res) {
        //             $data['u_id'] = intval($res);
        //             $this->getJoinPic($data['u_id'],$data['joinpic']);
        //             return apiResponse("200","授权成功",$data);
        //         }else{
        //             return apiResponse("201","授权失败","");
        //         }
        //     }
        // }
    }

    /**
     * 上传图片
     * @author topqiang
     * @DateTime 2018-09-03T14:46:43+0800
     * @return   [type]                   [description]
     */
    public function uploadPic()
    {
        $upload_res=$_FILES['pic'];
        $tempfile = file_get_contents($upload_res['tmp_name']);     // 把整个文件读入一个字符串中。

        $tagArr = explode(".", $upload_res['name']);
        $tag_sel = array_shift($tagArr);
        $tag_end = end($tagArr);

        $path = 'upload/'.uniqid().".".$tag_sel.".".$tag_end;
        $res = file_put_contents($path, $tempfile);                 // 把一个字符串写入文件中
        if( !empty($res)){
            return apiResponse(200,"上传成功！","/$path");
        }else{
            return apiResponse(201,"上传失败！",'');
        }
    }

    /**
     * 获取生成的小程序码
     * @author topqiang
     * @DateTime 2018-09-03T14:47:20+0800
     * @return   [type]                   [description]
     */
    public function getJoinPic($u_id="1",$picname){
        header('content-type:image/jpg');
        $accessToken = getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$accessToken";
        $data = array(
            'scene' => $u_id,
            'width' => 430,
            'page' => 'pages/firstPage/first'
            );
        $res = get_curl_request($url,"POST",json_encode($data));
        file_put_contents('1.jpg',$res);
        $dst = $this -> addCodePic('1.jpg');
        imagejpeg($dst,$picname);
    }


    /**
     * 添加水印
     * @author topqiang
     * @DateTime 2018-09-03T16:48:16+0800
     * @param    string                   $value [description]
     */
    public function addCodePic($src_pic){
        $dst_path = 'mystatic/bg3.png';
        //创建图片的实例
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        $src = imagecreatefromstring(file_get_contents($src_pic));
        //获取水印图片的宽高
        list($src_w, $src_h) = getimagesize($src_pic);
        //将水印图片复制到目标图片上，最后个参数50是设置透明度，这里实现半透明效果
        // imagecopymerge($dst, $src, 10, 10, 0, 0, $src_w, $src_h, 50);
        //如果水印图片本身带透明色，则使用imagecopy方法
        imagecopy($dst, $src, 790, 960, 0, 0, $src_w, $src_h);
        //输出图片
        return $dst;
    }
}